package com.ypz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ypz.reggie.common.R;
import com.ypz.reggie.entity.Employee;
import com.ypz.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 员工的管理
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登陆
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        //准备查询条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        //查询数据库
        Employee employeeResult = employeeService.getOne(lqw);

        //3、如果没有查询到则返回登录失败结果
        if (employeeResult == null) {
            return R.error("用户不存在");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!password.equals(employeeResult.getPassword())) {
            return R.error("密码错误");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (employeeResult.getStatus() == 0) {
            return R.error("该账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        HttpSession session = request.getSession();
        session.setAttribute("employee", employeeResult.getId());

        return R.success(employeeResult);
    }

    /**
     * 退出登陆，并返回登陆页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 创建用户
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //设置默认密码123456，用md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        公共字段填充
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //获取操作用户ID
//        Long createPerson = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(createPerson);
//        employee.setUpdateUser(createPerson);

        //调用服务层
        employeeService.save(employee);

        return R.success("保存成功");
    }

    /**
     * 分页查询和姓名搜索         知识点：get方法链接上的信息可以直接 接受,但是变量名必须和前端保持一致，不然会收不到参数
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Employee> iPage = new Page<>(page, pageSize);

        //查询条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lqw.orderByAsc(Employee::getName);

        //执行查询
        employeeService.page(iPage, lqw);
        return R.success(iPage);
    }

    /**
     * 根据ID查询员工信息
     * 修改员工信息时使用，进行信息的回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {

        Employee employee = employeeService.getById(id);

        return R.success(employee);
    }

    /**
     * 更新数据            知识点：如果传过来的是JSON数据就必须以对象接受，普通类型接受不了
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> modifyStatus(HttpServletRequest request, @RequestBody Employee employee) {
        //创建查询条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
        lqw.eq(Employee::getId, employee.getId());

        //公共字段填充，解决了这些数据
  /*      Long modifyId = (Long)request.getSession().getAttribute("employee");
        employee.setUpdateUser(modifyId);
        employee.setUpdateTime(LocalDateTime.now());*/

        employeeService.update(employee, lqw);

        return R.success("修改成功");
    }
}
